import 'package:cached_network_image/cached_network_image.dart';
import 'package:dartx/dartx.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:gluz/app/data/country_entity.dart';
import 'package:gluz/app/data/shop/shop_category_entity.dart';
import 'package:marquee/marquee.dart';
import 'package:gluz/app/utils/colors.dart';
import '../../../common/tabbar_indicator.dart';
import '../../../data/shop/shop_list_entity.dart';
import '../controllers/shop_controller.dart';

class ShopView extends GetView<ShopController> {
  const ShopView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: _buildAppBar(),
      body: RefreshIndicator(
        onRefresh: controller.onRefresh,
        child: GetBuilder<ShopController>(
          builder: (controller) {
            return CustomScrollView(
              physics: const AlwaysScrollableScrollPhysics(),
              slivers: [
                _buildPageTabs(),
                _buildSearchBar(),
                _buildMarqueeBar(),
                _buildPrimaryCategories(),
                _buildSecondaryCategoriesTabBar(),
                _buildProductList(),
                _buildLoadMoreIndicator(),
              ],
            );
          },
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
        onPressed: () => Get.back(),
      ),
      title: const Text(
        '商城',
        style: TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.bold,
          color: Colors.black,
        ),
      ),
      centerTitle: true,
    );
  }

  Widget _buildPageTabs() {
    return SliverToBoxAdapter(
      child: Container(
        color: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Row(
          children: [
            Obx(
              () => _buildTabItem(
                '商品',
                0,
                controller.selectedTabIndex.value == 0,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTabItem(String title, int index, bool isSelected) {
    return InkWell(
      onTap: () => controller.onTabChanged(index),
      child: Column(
        children: [
          Text(
            title,
            style: TextStyle(
              fontSize: 18,
              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
              color: Colors.black,
            ),
          ),
          const SizedBox(height: 8),
          if (isSelected)
            Container(
              height: 2,
              width: 20,
              decoration: BoxDecoration(
                color: AppColors.color_278AFF,
                borderRadius: BorderRadius.circular(1),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildSearchBar() {
    return SliverToBoxAdapter(
      child: Container(
        color: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: InkWell(
          onTap: controller.onSearchTap,
          child: Container(
            height: 40,
            decoration: BoxDecoration(
              color: AppColors.color_F7F7F7,
              borderRadius: BorderRadius.circular(20),
            ),
            child: Row(
              children: [
                const SizedBox(width: 12),
                Icon(Icons.search, color: AppColors.color_8C8C8C, size: 20),
                const SizedBox(width: 8),
                Text(
                  '搜索',
                  style: TextStyle(color: AppColors.color_8C8C8C, fontSize: 14),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildMarqueeBar() {
    return SliverToBoxAdapter(
      child: Container(
        color: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: Container(
          height: 32,
          decoration: BoxDecoration(
            color: const Color(0xFFFFF3CD),
            borderRadius: BorderRadius.circular(16),
          ),
          child: Row(
            children: [
              const SizedBox(width: 12),
              Icon(Icons.volume_up, color: AppColors.color_FF9800, size: 16),
              const SizedBox(width: 8),
              Expanded(
                child: Marquee(
                  text: '【小贴士】网购时请认准卖家资质、勿私下转账、保护个人信息, 安心购物!',
                  style: const TextStyle(
                    fontSize: 12,
                    color: AppColors.color_FF9800,
                  ),
                  scrollAxis: Axis.horizontal,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  blankSpace: 20.0,
                  velocity: 30.0,
                  pauseAfterRound: const Duration(seconds: 2),
                  startPadding: 10.0,
                  accelerationDuration: const Duration(seconds: 1),
                  accelerationCurve: Curves.linear,
                  decelerationDuration: const Duration(milliseconds: 500),
                  decelerationCurve: Curves.easeOut,
                ),
              ),
              const SizedBox(width: 8),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildPrimaryCategories() {
    return SliverToBoxAdapter(
      child: Container(
        color: Colors.white,
        child: SizedBox(
          height: 150.h,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            itemCount: controller.primaryCategories.length,
            itemBuilder: (context, index) {
              final category = controller.primaryCategories[index];
              ShopCategoryEntity? nextCategory;
              if (index + 1 < controller.primaryCategories.length) {
                nextCategory = controller.primaryCategories[index + 1];
              }
              ShopCategoryEntity? previousCategory;
              if (index - 1 >= 0) {
                previousCategory = controller.primaryCategories[index - 1];
              }
              if (category.aspectRatio > 1 &&
                  nextCategory != null &&
                  nextCategory.aspectRatio > 1) {
                return Column(
                  children: [
                    Expanded(
                      child: InkWell(
                        onTap: () {
                          controller.primaryCategory(category);
                        },
                        child: CachedNetworkImage(imageUrl: category.images),
                      ),
                    ),
                    Expanded(
                      child: InkWell(
                        onTap: () {
                          controller.primaryCategory(nextCategory!);
                        },
                        child: CachedNetworkImage(
                          imageUrl: nextCategory.images,
                        ),
                      ),
                    ),
                  ],
                );
              } else if (category.aspectRatio > 1 &&
                  previousCategory != null &&
                  previousCategory.aspectRatio > 1) {
                return SizedBox.shrink();
              }
              if (category.images.isEmpty) {
                return SizedBox.shrink();
              }
              return InkWell(
                onTap: () {
                  controller.primaryCategory(category);
                },
                child: CachedNetworkImage(imageUrl: category.images),
              );
            },
          ),
        ),
      ),
    );
  }

  Widget _buildSecondaryCategoriesTabBar() {
    return SliverToBoxAdapter(
      child: Row(
        children: [
          // 二级分类TabBar - 占用剩余空间
          if (controller.secondaryCategories.isNotEmpty &&
              controller.tabController != null)
            Expanded(
              child: SizedBox(
                height: 44,
                child: TabBar(
                  key: ValueKey(
                    controller.secondaryCategories.length,
                  ), // 添加key强制重建
                  controller: controller.tabController!,
                  isScrollable: true,
                  indicatorColor: AppColors.color_278AFF,
                  indicatorWeight: 4,
                  indicatorSize: TabBarIndicatorSize.label,
                  labelColor: AppColors.color_278AFF,
                  unselectedLabelColor: Colors.black,
                  dividerColor: Colors.transparent, // 移除底部灰色线条
                  tabAlignment: TabAlignment.center, // 左对齐
                  labelPadding: const EdgeInsets.symmetric(
                    horizontal: 20,
                  ), // 减少标签间距
                  labelStyle: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                  ),
                  unselectedLabelStyle: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.normal,
                  ),
                  indicator: TabBarCustomIndicator(),
                  tabs: controller.secondaryCategories.map((category) {
                    return Tab(child: Text(category.name));
                  }).toList(),
                  onTap: (index) => controller.onSecondaryCategoryTap(index),
                ),
              ),
            ),
          if (controller.secondaryCategories.isEmpty ||
              controller.tabController == null)
            Spacer(),
          // 筛选按钮 - 固定在右侧
          InkWell(
            onTap: controller.onFilterTap,
            child: Container(
              height: 44,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: CachedNetworkImage(
                imageUrl:
                    'https://gluz-oss.oss-cn-beijing.aliyuncs.com/shopstatic/filter.png',
                width: 22,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProductList() {
    // 如果没有商品数据，显示空状态
    if (controller.products.isEmpty) {
      return SliverToBoxAdapter(
        child: Container(
          height: 200,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.inventory_2_outlined,
                  size: 64,
                  color: Colors.grey[400],
                ),
                const SizedBox(height: 16),
                Text(
                  '暂无数据'.tr,
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.grey[600],
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }

    return SliverPadding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      sliver: SliverGrid(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 0.75,
          crossAxisSpacing: 12,
          mainAxisSpacing: 12,
        ),
        delegate: SliverChildBuilderDelegate((context, index) {
          // 如果是最后一个商品且还有更多数据，触发加载更多
          if (index == controller.products.length - 1 &&
              controller.hasMoreData &&
              !controller.isLoadingMore) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              controller.loadMoreProducts();
            });
          }

          final product = controller.products[index];
          return _buildProductItem(product);
        }, childCount: controller.products.length),
      ),
    );
  }

  Widget _buildLoadMoreIndicator() {
    return SliverToBoxAdapter(
      child: Container(
        padding: const EdgeInsets.all(16),
        child: Center(
          child: controller.isLoadingMore
              ? const CircularProgressIndicator()
              : controller.hasMoreData
              ? const SizedBox.shrink()
              : Text(
                  '没有更多商品了'.tr,
                  style: TextStyle(color: Colors.grey, fontSize: 14),
                ),
        ),
      ),
    );
  }

  Widget _buildProductItem(ShopListEntity product) {
    return InkWell(
      onTap: () => controller.onProductTap(product),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 4,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              height: 100,
              child: ClipRRect(
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(8),
                ),
                child: CachedNetworkImage(
                  imageUrl: product.getMainPicUrl(),
                  width: double.infinity,
                  fit: BoxFit.cover,
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(8),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      product.skuName,
                      style: const TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w500,
                        color: Colors.black,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            '¥${product.salesPrice}',
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: AppColors.color_F44336,
                            ),
                          ),
                        ),
                        Row(
                          children: [
                            Icon(
                              Icons.visibility,
                              size: 12,
                              color: AppColors.color_8C8C8C,
                            ),
                            const SizedBox(width: 4),
                            Text(
                              '${product.pageView}+',
                              style: TextStyle(
                                fontSize: 10,
                                color: AppColors.color_8C8C8C,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                    Image.asset('assets/images/shop/shop_dot_line.png'),
                    Expanded(
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          CircleAvatar(
                            foregroundImage: CachedNetworkImageProvider(product.userImg),
                            radius: 10,
                          ),
                          const SizedBox(width: 4),
                          Expanded(
                            child: Row(
                              children: [
                                Text(
                                  product.userName,
                                  style: TextStyle(
                                    fontSize: 10,
                                    color: AppColors.color_8C8C8C,
                                  ),
                                ),
                                const SizedBox(width: 5,),
                                CachedNetworkImage(imageUrl: product.getMemberLevelUrl(), width: 10,),
                              ],
                            ),
                          ),

                          const SizedBox(width: 5,),
                          CircleAvatar(
                            foregroundImage: AssetImage(CountryEntity.getCountryImage(product.userCountry)),
                            radius: 10,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
